/*
 * @Author: dingyuwen ding_yuwen@163.com
 * @Date: 2023-02-28 10:45:03
 * @LastEditTime: 2023-07-19 17:07:43
 * @LastEditors: DingYuwen 43669762+DingYuwen@users.noreply.github.com
 * @Description:
 */
import { Center, Spinner } from '@chakra-ui/react';
import {
  getCoreRowModel,
  getPaginationRowModel,
  PaginationState,
  useReactTable,
} from '@tanstack/react-table';
import { useContext, useEffect, useState } from 'react';
import { useQuery } from 'react-query';

import { ModelType, TrainingContext } from '..';

import ModelList from './ModelList';
import { ModelTrainingStatus } from './ModelStatus';

import trainService from '@/api/train.service';
export interface ModelTraining {
  id: string;
  name: string;
  triggerWords: string;
  modelDesc: string;
  status?: ModelTrainingStatus;
  type: number;
  remainTime?: number;
  [key: string]: any;
}

interface ModelListBoxProps {
  type: ModelType;
}
export default function ModelListBox(props: ModelListBoxProps) {
  const { modelChange } = useContext(TrainingContext);
  const { type } = props;
  const [{ pageIndex, pageSize }, setPagination] = useState<PaginationState>({
    pageIndex: 0,
    pageSize: 10,
  });
  const [models, setModels] = useState<ModelTraining[]>([]);

  const { data, isFetching } = useQuery(
    ['getUserModelByPageList', { pageIndex, pageSize, modelChange, type }],
    () =>
      trainService.getUserModelList({
        pageIndex,
        pageSize,
        type: type === 'lora' ? 2 : 1,
      }),
    { keepPreviousData: true, refetchOnWindowFocus: false }
  );

  const table = useReactTable({
    data: data?.rt?.records,
    pageCount: data?.rt?.pages ?? 1,
    state: {
      pagination: { pageIndex, pageSize },
    },
    columns: [],
    manualPagination: true,
    getCoreRowModel: getCoreRowModel(),
    onPaginationChange: setPagination,
    getPaginationRowModel: getPaginationRowModel(),
  });

  // const handleChange = () => {};

  useEffect(() => {
    setModels(data?.rt?.records || data?.rt || []);
  }, [data, type]);

  return (
    <>
      {isFetching && (
        <Center h="96">
          <Spinner />
        </Center>
      )}
      {!isFetching && (
        <ModelList models={models} table={data?.rt?.pages ? table : null} />
      )}
    </>
  );
}
